<template>
  <div class="inventory-dashboard">
    <h1 class="page-title">库存分析</h1>
    
    <!-- 库存概览统计 -->
    <el-row :gutter="20">
      <el-col :span="6" v-for="(stat, index) in inventoryStats" :key="index">
        <el-card class="stat-card">
          <div class="stat-value">{{ stat.format(animatedValues[index]) }}</div>
          <div class="stat-title">{{ stat.title }}</div>
          <div class="stat-change" :class="stat.trend">
            <el-icon>
              <component :is="stat.trend === 'up' ? 'ArrowUp' : 'ArrowDown'" />
            </el-icon>
            {{ stat.change }}
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 库存趋势和仓库分布 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 库存趋势图 -->
      <el-col :span="16">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <h3>库存趋势分析</h3>
              <div class="chart-controls">
                <el-select v-model="selectedCategory" size="small" placeholder="选择类别">
                  <el-option v-for="item in categories" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <el-radio-group v-model="timeRange" size="small" style="margin-left: 15px;">
                  <el-radio-button label="week">周</el-radio-button>
                  <el-radio-button label="month">月</el-radio-button>
                  <el-radio-button label="quarter">季度</el-radio-button>
                </el-radio-group>
              </div>
            </div>
          </template>
          <div class="chart" id="inventory-trend-chart"></div>
        </el-card>
      </el-col>
      
      <!-- 仓库分布 -->
      <el-col :span="8">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <h3>仓库库存占比</h3>
            </div>
          </template>
          <div class="chart" id="warehouse-distribution-chart"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 库存分类和预警信息 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 库存分类 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <h3>库存分类占比</h3>
            </div>
          </template>
          <div class="chart" id="inventory-category-chart"></div>
        </el-card>
      </el-col>
      
      <!-- 库存预警 -->
      <el-col :span="12">
        <el-card class="warning-card">
          <template #header>
            <div class="chart-header">
              <h3>库存预警</h3>
              <el-tag type="danger">{{ warningItems.length }}项</el-tag>
            </div>
          </template>
          <el-table :data="warningItems" style="width: 100%" max-height="310">
            <el-table-column prop="name" label="产品名称" width="180" />
            <el-table-column prop="category" label="类别" width="100" />
            <el-table-column prop="warehouse" label="仓库" width="100" />
            <el-table-column prop="current" label="当前库存" width="100" />
            <el-table-column prop="warning" label="预警类型" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.warning === '库存不足' ? 'danger' : 'warning'">
                  {{ scope.row.warning }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="action" label="操作">
              <template #default>
                <el-button link type="primary">处理</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 库存周转和有效期 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 周转率排行 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <h3>库存周转率排行（按类别）</h3>
            </div>
          </template>
          <div class="chart" id="turnover-chart"></div>
        </el-card>
      </el-col>
      
      <!-- 临近效期 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <h3>临近效期库存</h3>
            </div>
          </template>
          <div class="chart" id="expiry-chart"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'

// 库存统计数据
const inventoryStats = [
  {
    title: '总库存金额',
    value: '￥9,876,543',
    numericValue: 9876543,
    format: (val: number) => `￥${val.toLocaleString()}`,
    change: '2.8%',
    trend: 'up'
  },
  {
    title: '库存总量',
    value: '24,685',
    numericValue: 24685,
    format: (val: number) => val.toLocaleString(),
    change: '3.5%',
    trend: 'up'
  },
  {
    title: '平均周转天数',
    value: '15.3天',
    numericValue: 15.3,
    format: (val: number) => `${val.toFixed(1)}天`,
    change: '4.2%',
    trend: 'down'
  },
  {
    title: '滞销产品数',
    value: '42',
    numericValue: 42,
    format: (val: number) => Math.round(val).toString(),
    change: '12.5%',
    trend: 'down'
  }
]

// 动画显示的值
const animatedValues = ref(inventoryStats.map(() => 0))

// 动画效果函数
const animateValues = () => {
  // 为每个卡片创建动画
  inventoryStats.forEach((stat, index) => {
    const targetValue = stat.numericValue
    const duration = 2000 // 动画持续2秒
    const startTime = Date.now()
    
    const animate = () => {
      const currentTime = Date.now()
      const elapsed = currentTime - startTime
      
      if (elapsed < duration) {
        // 使用easeOutExpo缓动函数让动画更自然
        const progress = 1 - Math.pow(1 - elapsed / duration, 3)
        animatedValues.value[index] = targetValue * progress
        requestAnimationFrame(animate)
      } else {
        animatedValues.value[index] = targetValue
      }
    }
    
    animate()
  })
}

// 过滤选项
const selectedCategory = ref('all')
const timeRange = ref('month')
const categories = [
  { label: '所有类别', value: 'all' },
  { label: '原材料', value: 'materials' },
  { label: '半成品', value: 'semifinished' },
  { label: '成品', value: 'finished' },
  { label: '包装物', value: 'packaging' }
]

// 库存预警数据
const warningItems = [
  {
    name: '高性能处理器',
    category: '电子元件',
    warehouse: '华东仓',
    current: 50,
    warning: '库存不足'
  },
  {
    name: '智能手表外壳',
    category: '塑料件',
    warehouse: '华南仓',
    current: 1200,
    warning: '库存积压'
  },
  {
    name: '钛合金外壳',
    category: '金属件',
    warehouse: '华北仓',
    current: 30,
    warning: '库存不足'
  },
  {
    name: '有机玻璃',
    category: '原材料',
    warehouse: '西南仓',
    current: 800,
    warning: '库存积压'
  },
  {
    name: '特殊电池',
    category: '电子元件',
    warehouse: '华东仓',
    current: 20,
    warning: '库存不足'
  },
  {
    name: '包装纸盒',
    category: '包装物',
    warehouse: '华南仓',
    current: 5000,
    warning: '临近效期'
  },
  {
    name: 'LED屏幕',
    category: '显示组件',
    warehouse: '华东仓',
    current: 45,
    warning: '库存不足'
  }
]

// 图表实例
let trendChart: echarts.ECharts | null = null
let warehouseChart: echarts.ECharts | null = null
let categoryChart: echarts.ECharts | null = null
let turnoverChart: echarts.ECharts | null = null
let expiryChart: echarts.ECharts | null = null

// 初始化库存趋势图
const initTrendChart = () => {
  if (!trendChart) {
    trendChart = echarts.init(document.getElementById('inventory-trend-chart') as HTMLElement)
  }
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['入库量', '出库量', '库存量']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    },
    yAxis: {
      type: 'value',
      name: '数量'
    },
    series: [
      {
        name: '入库量',
        type: 'bar',
        stack: 'total',
        emphasis: {
          focus: 'series'
        },
        data: [320, 302, 301, 334, 390, 330, 320, 301, 334, 390, 330, 320]
      },
      {
        name: '出库量',
        type: 'bar',
        stack: 'total',
        emphasis: {
          focus: 'series'
        },
        data: [120, 132, 101, 134, 90, 230, 210, 132, 101, 134, 90, 230]
      },
      {
        name: '库存量',
        type: 'line',
        emphasis: {
          focus: 'series'
        },
        data: [820, 932, 901, 934, 1290, 1330, 1320, 1001, 1134, 990, 1230, 1310]
      }
    ]
  }
  
  trendChart.setOption(option)
}

// 初始化仓库分布图
const initWarehouseChart = () => {
  if (!warehouseChart) {
    warehouseChart = echarts.init(document.getElementById('warehouse-distribution-chart') as HTMLElement)
  }
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: ['华东仓', '华南仓', '华北仓', '西南仓', '西北仓']
    },
    series: [
      {
        name: '库存占比',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 20,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 1048, name: '华东仓' },
          { value: 735, name: '华南仓' },
          { value: 580, name: '华北仓' },
          { value: 484, name: '西南仓' },
          { value: 300, name: '西北仓' }
        ]
      }
    ]
  }
  
  warehouseChart.setOption(option)
}

// 初始化库存分类图
const initCategoryChart = () => {
  if (!categoryChart) {
    categoryChart = echarts.init(document.getElementById('inventory-category-chart') as HTMLElement)
  }
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      top: '10%',
      left: 'center'
    },
    series: [
      {
        name: '库存分类',
        type: 'pie',
        radius: ['30%', '80%'],
        roseType: 'area',
        itemStyle: {
          borderRadius: 5
        },
        data: [
          { value: 40, name: '电子元件' },
          { value: 38, name: '塑料件' },
          { value: 32, name: '金属件' },
          { value: 30, name: '包装物' },
          { value: 28, name: '原材料' },
          { value: 26, name: '半成品' },
          { value: 22, name: '成品' },
          { value: 18, name: '其他' }
        ]
      }
    ]
  }
  
  categoryChart.setOption(option)
}

// 初始化周转率排行图
const initTurnoverChart = () => {
  if (!turnoverChart) {
    turnoverChart = echarts.init(document.getElementById('turnover-chart') as HTMLElement)
  }
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      name: '周转率'
    },
    yAxis: {
      type: 'category',
      data: ['电子元件', '成品', '半成品', '原材料', '塑料件', '金属件', '包装物'],
      axisLabel: {
        formatter: (value: string) => {
          if (value.length > 10) {
            return value.substring(0, 10) + '...'
          }
          return value
        }
      }
    },
    series: [
      {
        name: '周转率',
        type: 'bar',
        data: [4.5, 3.8, 3.2, 2.8, 2.5, 2.1, 1.8]
      }
    ]
  }
  
  turnoverChart.setOption(option)
}

// 初始化临近效期图
const initExpiryChart = () => {
  if (!expiryChart) {
    expiryChart = echarts.init(document.getElementById('expiry-chart') as HTMLElement)
  }
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['30天内', '60天内', '90天内']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['原材料', '半成品', '成品', '包装物']
    },
    yAxis: {
      type: 'value',
      name: '数量'
    },
    series: [
      {
        name: '30天内',
        type: 'bar',
        emphasis: {
          focus: 'series'
        },
        stack: 'Ad',
        data: [120, 80, 30, 150]
      },
      {
        name: '60天内',
        type: 'bar',
        stack: 'Ad',
        emphasis: {
          focus: 'series'
        },
        data: [80, 120, 60, 90]
      },
      {
        name: '90天内',
        type: 'bar',
        stack: 'Ad',
        emphasis: {
          focus: 'series'
        },
        data: [50, 60, 100, 40]
      }
    ]
  }
  
  expiryChart.setOption(option)
}

// 自适应图表大小
const handleResize = () => {
  trendChart?.resize()
  warehouseChart?.resize()
  categoryChart?.resize()
  turnoverChart?.resize()
  expiryChart?.resize()
}

// 在组件挂载后初始化图表
onMounted(() => {
  // 初始化所有图表
  initTrendChart()
  initWarehouseChart()
  initCategoryChart()
  initTurnoverChart()
  initExpiryChart()
  
  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize)
  
  // 启动数值动画
  animateValues()
})

// 在组件卸载前销毁图表实例
onBeforeUnmount(() => {
  if (trendChart) {
    trendChart.dispose()
    trendChart = null
  }
  if (warehouseChart) {
    warehouseChart.dispose()
    warehouseChart = null
  }
  if (categoryChart) {
    categoryChart.dispose()
    categoryChart = null
  }
  if (turnoverChart) {
    turnoverChart.dispose()
    turnoverChart = null
  }
  if (expiryChart) {
    expiryChart.dispose()
    expiryChart = null
  }
  
  // 移除窗口大小变化监听
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.inventory-dashboard {
  padding: 20px;
}

.page-title {
  font-size: 24px;
  margin-bottom: 20px;
  color: #303133;
}

/* 统计卡片样式 */
.stat-card {
  min-height: 120px;
  text-align: center;
  /* padding: 20px 0; */
  position: relative;
  overflow: hidden;
  background: linear-gradient(to right, #f8f9fa, #ffffff);
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
}

.stat-title {
  font-size: 16px;
  color: #909399;
  margin-bottom: 8px;
}

.stat-change {
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.stat-change.up {
  color: #67C23A;
}

.stat-change.down {
  color: #F56C6C;
}

/* 图表卡片样式 */
.chart-card {
  margin-bottom: 20px;
  height: 400px;
}

.warning-card {
  margin-bottom: 20px;
  height: 400px;
}

.chart {
  width: 100%;
  height: 330px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.chart-controls {
  display: flex;
  align-items: center;
}

@media screen and (max-width: 768px) {
  .el-col {
    margin-bottom: 15px;
  }
  
  .chart-card, .warning-card {
    height: auto;
  }
  
  .chart {
    height: 250px;
  }
}
</style> 